#Boa:Dialog:Dialog1

import wx
import wx.grid
import consultasBD
import utiles

def create(parent):
    return Dialog1(parent)

[wxID_DIALOG1, wxID_DIALOG1BUTTON1, wxID_DIALOG1BUTTON2, wxID_DIALOG1BUTTON3, 
 wxID_DIALOG1BUTTON4, wxID_DIALOG1BUTTON5, wxID_DIALOG1CHECKBOX1, 
 wxID_DIALOG1CHECKBOX2, wxID_DIALOG1CHECKBOX3, wxID_DIALOG1CHECKBOX4, 
 wxID_DIALOG1CHECKBOX5, wxID_DIALOG1CHECKBOX6, wxID_DIALOG1COMBOBOX1, 
 wxID_DIALOG1COMBOBOX2, wxID_DIALOG1COMBOBOX3, wxID_DIALOG1COMBOBOX4, 
 wxID_DIALOG1GRID1, wxID_DIALOG1STATICBOX1, wxID_DIALOG1STATICTEXT1, 
 wxID_DIALOG1STATICTEXT2, wxID_DIALOG1STATICTEXT3, wxID_DIALOG1STATICTEXT4, 
 wxID_DIALOG1STATICTEXT5, wxID_DIALOG1STATICTEXT6, wxID_DIALOG1STATICTEXT7, 
 wxID_DIALOG1TEXTCTRL1, wxID_DIALOG1TEXTCTRL2, wxID_DIALOG1TEXTCTRL3, 
] = [wx.NewId() for _init_ctrls in range(28)]

class Dialog1(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DIALOG1, name='', parent=prnt,
              pos=wx.Point(10, 9), size=wx.Size(1017, 575),
              style=wx.DEFAULT_DIALOG_STYLE, title='Listado de Stock')
        self.SetClientSize(wx.Size(1009, 548))

        self.textCtrl1 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL1, name='textCtrl1',
              parent=self, pos=wx.Point(16, 24), size=wx.Size(88, 21), style=0,
              value='')

        self.textCtrl2 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL2, name='textCtrl2',
              parent=self, pos=wx.Point(104, 24), size=wx.Size(192, 21),
              style=0, value='')

        self.button1 = wx.Button(id=wxID_DIALOG1BUTTON1, label='Buscar',
              name='button1', parent=self, pos=wx.Point(216, 48),
              size=wx.Size(80, 23), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnBuscarProveedor,
              id=wxID_DIALOG1BUTTON1)

        self.staticText2 = wx.StaticText(id=wxID_DIALOG1STATICTEXT2,
              label='Estacion', name='staticText2', parent=self,
              pos=wx.Point(312, 8), size=wx.Size(40, 13), style=0)

        self.comboBox1 = wx.ComboBox(choices=["Verano", "Primavera", "Otono",
              "Invierno", "Lince-Vera", "Lince-Prim", "Lince-Oton",
              "Lince-Invi"], id=wxID_DIALOG1COMBOBOX1, name='comboBox1',
              parent=self, pos=wx.Point(312, 24), size=wx.Size(104, 21),
              style=0, value='')
        self.comboBox1.SetLabel('')

        self.staticText3 = wx.StaticText(id=wxID_DIALOG1STATICTEXT3,
              label='Anio', name='staticText3', parent=self, pos=wx.Point(420,
              8), size=wx.Size(21, 13), style=0)

        self.staticText4 = wx.StaticText(id=wxID_DIALOG1STATICTEXT4,
              label='Grupo', name='staticText4', parent=self, pos=wx.Point(488,
              8), size=wx.Size(29, 13), style=0)

        self.comboBox2 = wx.ComboBox(choices=[], id=wxID_DIALOG1COMBOBOX2,
              name='comboBox2', parent=self, pos=wx.Point(420, 24),
              size=wx.Size(64, 21), style=0, value='')
        self.comboBox2.SetLabel('')

        self.comboBox3 = wx.ComboBox(choices=[], id=wxID_DIALOG1COMBOBOX3,
              name='comboBox3', parent=self, pos=wx.Point(488, 24),
              size=wx.Size(130, 21), style=0, value='')
        self.comboBox3.SetLabel('')

        self.comboBox4 = wx.ComboBox(choices=[], id=wxID_DIALOG1COMBOBOX4,
              name='comboBox4', parent=self, pos=wx.Point(624, 24),
              size=wx.Size(136, 21), style=0, value='')
        self.comboBox4.SetLabel('')
        self.comboBox4.Bind(wx.EVT_COMBOBOX, self.OnCambiaRubro,
              id=wxID_DIALOG1COMBOBOX4)

        self.checkBox1 = wx.CheckBox(id=wxID_DIALOG1CHECKBOX1,
              label='Incluir stock 0', name='checkBox1', parent=self,
              pos=wx.Point(312, 56), size=wx.Size(96, 13), style=0)
        self.checkBox1.SetValue(False)

        self.checkBox2 = wx.CheckBox(id=wxID_DIALOG1CHECKBOX2,
              label='Incluir stock negativo', name='checkBox2', parent=self,
              pos=wx.Point(312, 72), size=wx.Size(128, 13), style=0)
        self.checkBox2.SetValue(False)

        self.checkBox4 = wx.CheckBox(id=wxID_DIALOG1CHECKBOX4,
              label='Incluir estaciones asociadas', name='checkBox4',
              parent=self, pos=wx.Point(440, 56), size=wx.Size(160, 13),
              style=0)
        self.checkBox4.SetValue(True)

        self.staticText5 = wx.StaticText(id=wxID_DIALOG1STATICTEXT5,
              label='* TODOS los proveedores', name='staticText5', parent=self,
              pos=wx.Point(16, 48), size=wx.Size(124, 13), style=0)

        self.checkBox5 = wx.CheckBox(id=wxID_DIALOG1CHECKBOX5,
              label='Excluir anio actual ', name='checkBox5', parent=self,
              pos=wx.Point(656, 56), size=wx.Size(152, 13), style=0)
        self.checkBox5.SetValue(False)

        self.checkBox3 = wx.CheckBox(id=wxID_DIALOG1CHECKBOX3,
              label='Excluir stock mayor a cero', name='checkBox3', parent=self,
              pos=wx.Point(312, 88), size=wx.Size(144, 13), style=0)
        self.checkBox3.SetValue(False)

        self.button5 = wx.Button(id=wxID_DIALOG1BUTTON5, label='Procesar',
              name='button5', parent=self, pos=wx.Point(768, 24),
              size=wx.Size(75, 23), style=0)
        self.button5.Bind(wx.EVT_BUTTON, self.OnProcesar,
              id=wxID_DIALOG1BUTTON5)

        self.button3 = wx.Button(id=wxID_DIALOG1BUTTON3, label='Imprimir',
              name='button3', parent=self, pos=wx.Point(848, 24),
              size=wx.Size(75, 23), style=0)
        self.button3.Bind(wx.EVT_BUTTON, self.OnImprimir,
              id=wxID_DIALOG1BUTTON3)

        self.button4 = wx.Button(id=wxID_DIALOG1BUTTON4, label='Limpiar',
              name='button4', parent=self, pos=wx.Point(926, 24),
              size=wx.Size(75, 23), style=0)
        self.button4.Bind(wx.EVT_BUTTON, self.OnLimpiar, id=wxID_DIALOG1BUTTON4)

        self.button2 = wx.Button(id=wxID_DIALOG1BUTTON2, label='Salir',
              name='button2', parent=self, pos=wx.Point(926, 56),
              size=wx.Size(75, 23), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnSalir, id=wxID_DIALOG1BUTTON2)

        self.grid1 = wx.grid.Grid(id=wxID_DIALOG1GRID1, name='grid1',
              parent=self, pos=wx.Point(8, 120), size=wx.Size(992, 416),
              style=0)

        self.staticText6 = wx.StaticText(id=wxID_DIALOG1STATICTEXT6,
              label='(Invierno+Otono / Verano+Primavera)', name='staticText6',
              parent=self, pos=wx.Point(456, 72), size=wx.Size(186, 13),
              style=0)

        self.staticBox1 = wx.StaticBox(id=wxID_DIALOG1STATICBOX1,
              label='Proveedor', name='staticBox1', parent=self, pos=wx.Point(8,
              8), size=wx.Size(296, 72), style=0)

        self.textCtrl3 = wx.TextCtrl(id=wxID_DIALOG1TEXTCTRL3, name='textCtrl3',
              parent=self, pos=wx.Point(848, 56), size=wx.Size(48, 21), style=0,
              value='')
        self.textCtrl3.SetEditable(False)

        self.staticText1 = wx.StaticText(id=wxID_DIALOG1STATICTEXT1,
              label='(no usar con el boton Buscar)', name='staticText1',
              parent=self, pos=wx.Point(24, 62), size=wx.Size(141, 13),
              style=0)

        self.staticText7 = wx.StaticText(id=wxID_DIALOG1STATICTEXT7,
              label='Rubro', name='staticText7', parent=self, pos=wx.Point(624,
              8), size=wx.Size(29, 13), style=0)

        self.checkBox6 = wx.CheckBox(id=wxID_DIALOG1CHECKBOX6,
              label='Incluir Stock otras sucursales', name='checkBox6',
              parent=self, pos=wx.Point(656, 72), size=wx.Size(168, 13),
              style=0)
        self.checkBox6.SetValue(False)
        self.checkBox6.Bind(wx.EVT_CHECKBOX, self.OnCheck6,
              id=wxID_DIALOG1CHECKBOX6)

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.checkBox2.SetValue(True)
        self.checkBox4.SetValue(True)
        anio = utiles.obtenerFecha("Y-m-d")[:4]
        self.checkBox5.SetLabel("Excluir anio actual ("+anio+")")
        self.sucursal = utiles.getSucursalActiva()
        self.crearGrillas()
        self.cargarCombos()

    def OnSalir(self, event):
        self.Close()

    def OnBuscarProveedor(self, event):
        if self.textCtrl1.GetValue() != "":
            consultaSQL = "SELECT idproveedor,nombre FROM proveedor WHERE idproveedor = '"+self.textCtrl1.GetValue()+"' "
            resultado = consultasBD.ordenCrudaDict(consultaSQL)
            if resultado != ():
                proveedor = resultado[0]
                self.textCtrl1.SetLabel(proveedor["idproveedor"])
                self.textCtrl2.SetLabel(proveedor["nombre"])
                self.comboBox1.SetFocus()
                return
            self.textCtrl1.SetLabel("")
            self.textCtrl2.SetLabel("")
            self.textCtrl1.SetFocus()
            return
        if self.textCtrl2.GetValue() != "":
            consultaSQL = "SELECT idproveedor,nombre FROM proveedor WHERE nombre LIKE '%"+self.textCtrl2.GetValue()+"%' "
            resultado = consultasBD.ordenCrudaDict(consultaSQL)
            if resultado != () and len(resultado)==1:
                proveedor = resultado[0]
                self.textCtrl1.SetLabel(proveedor["idproveedor"])
                self.textCtrl2.SetLabel(proveedor["nombre"])
                self.comboBox1.SetFocus()
                return
        import BuscaProveedor2
        ventana = BuscaProveedor2.Dialog1(self,self.textCtrl2.GetLabel())
        try:
            ventana.ShowModal()
            eleccion = ventana.getSeleccion()
        finally:
            ventana.Destroy()
        if eleccion.split(" / ") != ['']:
            self.textCtrl1.SetValue(eleccion.split(" / ")[1])
            self.textCtrl2.SetValue(eleccion.split(" / ")[0])
            self.comboBox1.SetFocus()
        else:
            self.textCtrl1.SetFocus()

    def OnLimpiar(self, event):
        self.grid1.ClearGrid()
        for fil in xrange(self.grid1.GetNumberRows()):
            self.grid1.DeleteRows()
        self.grid1.AppendRows()
        self.textCtrl1.SetLabel("")
        self.textCtrl2.SetLabel("")
        self.comboBox1.SetSelection(-1)
        self.comboBox2.SetSelection(-1)
        self.comboBox3.SetSelection(-1)
        self.comboBox3.Enable(True)
        self.comboBox4.SetSelection(-1)
        self.checkBox1.SetValue(False)
        self.checkBox2.SetValue(True)
        self.checkBox3.SetValue(False)
        self.checkBox4.SetValue(True)
        self.checkBox5.SetValue(False)
        self.textCtrl1.SetFocus()

    def crearGrillas(self):
        #ptc,codsussan,descripcion,proveedor,talle,color,grupo,estacion,anio,stock
        #0   1         2           3         4     5     6     7        8    9
        columnas = ['P.T.C','Codigo\nSussan','Descripcion','Proveedor','Talle','Color','Grupo','Estacion','Anio','Stock']
        self.grid1.CreateGrid(1,len(columnas))
        for i, col in enumerate(columnas): 
            self.grid1.SetColLabelValue(i, col)

        self.ajustarAnchoColumnas()
        self.grid1.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
        self.grid1.Refresh()
        
    def ajustarAnchoColumnas(self):
        for y in xrange(self.grid1.GetNumberCols()):
            self.grid1.AutoSizeColumn(y,True)

    def cargarCombos(self):
        anioActual = int(utiles.getfecha()[-4:])
        primerAnio = 2008
        for i in xrange(anioActual-primerAnio+1):
            aux = primerAnio + i
            self.comboBox2.Append(str(aux))
        
        sql = "SELECT nombregrupo,idgrupo FROM grupos WHERE 1 ORDER BY nombregrupo"
        resultados = consultasBD.ordenCruda(sql)
        for item in resultados:
            cadena = str(item[0])+" / "+str(item[1])
            self.comboBox3.Append(cadena)

        sql = "SELECT nombrerubro,idrubro FROM rubros WHERE 1 GROUP BY nombrerubro ORDER BY nombrerubro"
        resultados = consultasBD.ordenCruda(sql)
        self.comboBox4.Append("sin especificar")
        for item in resultados:
            cadena = str(item[0])+" / "+str(item[1])
            self.comboBox4.Append(cadena)
            
        self.comboBox1.SetEditable(False)
        self.comboBox2.SetEditable(False)
        self.comboBox3.SetEditable(False)
        self.comboBox4.SetEditable(False)

    def condiciones(self,listaGrupos):
        aux = [0,0,0]
        if self.checkBox1.GetValue():#incluir stock 0
            aux[0] = 1
        if self.checkBox2.GetValue():#incluir stock negativo
            aux[1] = 1
        if self.checkBox3.GetValue():#excluir stock mayor a cero
            aux[2] = 1

        condicion1 = ""
        if not self.checkBox6.GetValue():
            if   aux == [0,0,0]:
                condicion1 = " AND stock>0 "
            elif aux == [0,0,1]:
                texto = "Las condiciones seleccionadas hacen\n"
                texto+= "imposible generar el listado (1)"
                utiles.mensaje(None,texto)
                return False,"","","","",""
            elif aux == [0,1,0]:
                condicion1 = " AND stock<>0 "
            elif aux == [0,1,1]:
                condicion1 = " AND stock<0 "
            elif aux == [1,0,0]:
                condicion1 = " AND stock>=0 "
            elif aux == [1,0,1]:
                condicion1 = " AND stock=0 "
            elif aux == [1,1,0]:
                condicion1 = ""
            elif aux == [1,1,1]:
                condicion1 = " AND stock<=0 "
            else:
                pass
        else: #[0,1,0]
            condicion1 = " AND stock<>0 "

        condicion2 = ""
        estacion = self.comboBox1.GetLabel()
        if estacion!="":
            if self.checkBox4.GetValue():
                if estacion=="Invierno" or estacion=="Otono" or estacion=="Lince-Invi" or estacion=="Lince-Oton":
                    condicion2 = " AND (p4.estacion LIKE '%Invi%' OR p4.estacion LIKE '%Oton%') "
                if estacion=="Verano" or estacion=="Primavera" or estacion=="Lince-Vera" or estacion=="Lince-Prim":
                    condicion2 = " AND (p4.estacion LIKE '%Vera%' OR p4.estacion LIKE '%Prim%') "
            else:
                condicion2 = " AND p4.estacion='"+self.comboBox1.GetLabel()+"' "

        condicion3 = ""
        anio1 = utiles.obtenerFecha("Y-m-d")[:4]
        anio2 = self.comboBox2.GetLabel()
        if anio2!="":
            if anio1==anio2 and self.checkBox5.GetValue():
                texto = "Las condiciones seleccionadas hacen\n"
                texto+= "imposible generar el listado (2)"
                utiles.mensaje(None,texto)
                return False,"","","","",""
            condicion3+= " AND anio='"+anio2+"' "
        if self.checkBox5.GetValue():
            condicion3+= " AND anio<>'"+anio1+"' "
            
        condicion4 = ""
        idproveedor = self.textCtrl1.GetLabel()
        if idproveedor=="":
            texto = "Debe especificar un Codigo de Proveedor"
            utiles.mensaje(None,texto)
            return False,"","","","",""
        if idproveedor!="*":
            condicion4 = " AND p5.proveedor='"+idproveedor+"' "
            
        condicion5 = ""
        if listaGrupos == []:
            if self.comboBox3.GetLabel()!="":
                nombre,grupo = (self.comboBox3.GetLabel()).split(" / ")
                if grupo!="":
                    condicion5 = " AND p4.grupo='"+grupo+"' "
        else:
            condicion5 = " AND p4.grupo IN ("
            for item in listaGrupos:
                condicion5+= "'"+str(item)+"',"
            condicion5 = condicion5[:-1]+") "
            
        return True,condicion1,condicion2,condicion3,condicion4,condicion5
        
    def sqlTotal(self):
        listaGrupos = []
        if self.comboBox4.GetSelection()>0:
            rubro = (self.comboBox4.GetLabel().split(" / "))[1]
            sql = "SELECT idgrupo FROM rubros WHERE idrubro='"+rubro+"'"
            resultado = consultasBD.ordenCruda(sql)
            for item in resultado:
                listaGrupos.append(item[0])
        ok,condicion1,condicion2,condicion3,condicion4,condicion5 = self.condiciones(listaGrupos)
        if not ok:
            return False,""

        r1 = "SELECT p7.ptc,p7.codsussan,p7.descri,p7.stock,p7.anio,p7.estacion, \n"
        r2 = "       p7.grupo,p8.nombregrupo,p7.proveedor,p7.nombre,p7.talle,p7.color \n"
        r3 = "FROM \n"
        r4 = "    (SELECT p5.ptc,p5.codsussan,p5.descri,p5.stock,p5.anio,p5.estacion, \n"
        r5 = "     p5.grupo,p5.proveedor,p6.nombre,p5.talle,p5.color \n"
        r6 = "     FROM \n"
        r7 = "         (SELECT p3.ptc,p3.codsussan,p4.descri,p3.stock, \n"
        r8 = "          p4.anio,p4.grupo,p4.estacion,p4.proveedor,p3.talle,p3.color \n"
        r9 = "          FROM \n"
        r0 = "              (SELECT p1.ptc,p2.codsussan,p1.stock,p2.talle,p2.color \n"
        rA = "               FROM \n"
        rB = "                   (SELECT ptc,stock FROM stock \n"
        rB1 = "                   WHERE sucursal='"+self.sucursal+"' \n"
        rB2 = "                   "+condicion1+") AS p1, \n"
        rC = "                    producto_talle_color AS p2 \n"
        rD = "               WHERE p1.ptc=p2.id) AS p3, \n"
        rE = "               productos AS p4 \n"
        rF = "          WHERE p3.codsussan=p4.codsussan \n"
        rF1 = "               "+condicion2+condicion3+condicion5+") AS p5, \n"
        rG = "          proveedor AS p6 \n"
        rH = "     WHERE p6.idproveedor=p5.proveedor "+condicion4+") AS p7, \n"
        rI = "     grupos AS p8 \n"
        rJ = "WHERE p7.grupo=p8.idgrupo ORDER BY p7.nombre,p7.estacion,p7.anio,p7.codsussan,p7.ptc "
        sql = r1+r2+r3+r4+r5+r6+r7+r8+r9+r0+rA+rB+rB1+rB2+rC+rD+rE+rF+rF1+rG+rH+rI+rJ
        print "1->",sql
        resultados = consultasBD.ordenCrudaDict(sql)
        return True,resultados

    def sqlSucursales(self):
        listaGrupos = []
        if self.comboBox4.GetSelection()>0:
            rubro = (self.comboBox4.GetLabel().split(" / "))[1]
            sql = "SELECT idgrupo FROM rubros WHERE idrubro='"+rubro+"'"
            resultado = consultasBD.ordenCruda(sql)
            for item in resultado:
                listaGrupos.append(item[0])
        ok,condicion1,condicion2,condicion3,condicion4,condicion5 = self.condiciones(listaGrupos)

        r1 = "SELECT p7.ptc,p7.codsussan,p7.descri,p7.sucursal,p7.stock,p7.anio,p7.estacion, \n"
        r2 = "       p7.grupo,p8.nombregrupo,p7.proveedor,p7.nombre,p7.talle,p7.color \n"
        r3 = "FROM \n"
        r4 = "    (SELECT p5.ptc,p5.codsussan,p5.descri,p5.sucursal,p5.stock,p5.anio,p5.estacion, \n"
        r5 = "     p5.grupo,p5.proveedor,p6.nombre,p5.talle,p5.color \n"
        r6 = "     FROM \n"
        r7 = "         (SELECT p3.ptc,p3.codsussan,p4.descri,p3.sucursal,p3.stock, \n"
        r8 = "          p4.anio,p4.grupo,p4.estacion,p4.proveedor,p3.talle,p3.color \n"
        r9 = "          FROM \n"
        r0 = "              (SELECT p1.ptc,p2.codsussan,p1.sucursal,p1.stock,p2.talle,p2.color \n"
        rA = "               FROM \n"
        rB = "                   (SELECT * FROM \n"
        rB1= "                    (SELECT ptc,stock,sucursal FROM stock WHERE sucursal='1' AND stock<>0 \n"
        rB2= "                     UNION \n"
        rB3= "                     SELECT ptc,stock,sucursal FROM stock WHERE sucursal='2' AND stock<>0 \n"
        rB4= "                     UNION \n"
        rB5= "                     SELECT ptc,stock,sucursal FROM stock WHERE sucursal='3' AND stock<>0 \n"
        rB6= "                     UNION \n"
        rB7= "                     SELECT ptc,stock,sucursal FROM stock WHERE sucursal='4' AND stock<>0) AS p \n"
        rB8= "                     WHERE 1 ORDER BY ptc) AS p1, \n"
        rC = "                    producto_talle_color AS p2 \n"
        rD = "               WHERE p1.ptc=p2.id) AS p3, \n"
        rE = "               productos AS p4 \n"
        rF = "          WHERE p3.codsussan=p4.codsussan \n"
        rF1 = "               "+condicion2+condicion3+condicion5+") AS p5, \n"
        rG = "          proveedor AS p6 \n"
        rH = "     WHERE p6.idproveedor=p5.proveedor "+condicion4+") AS p7, \n"
        rI = "     grupos AS p8 \n"
        rJ = "WHERE p7.grupo=p8.idgrupo ORDER BY p7.nombre,p7.estacion,p7.anio,p7.codsussan,p7.ptc,p7.sucursal "
        sql = r1+r2+r3+r4+r5+r6+r7+r8+r9+r0+rA+rB+rB1+rB2+rB3+rB4+rB5+rB6+rB7+rB8+rC+rD+rE+rF+rF1+rG+rH+rI+rJ
        resultados = consultasBD.ordenCrudaDict(sql)
        return True,resultados

    def obtenerColor(self,color):
        sql = "SELECT nombre FROM colores WHERE idcolor='"+color+"' "
        resultado = consultasBD.ordenCruda(sql)
        if len(resultado)!=1 or resultado==None or resultado==():
            return ""
        return resultado[0][0]

    def OnProcesar(self, event):
        if not self.checkBox6.GetValue():
            ok,datos = self.sqlTotal()
        else: #trae stock de sucursales
            ok,datos = self.sqlSucursales()
        if not ok:
            return
        self.grid1.ClearGrid()
        for fil in xrange(self.grid1.GetNumberRows()):
            self.grid1.DeleteRows()
        self.grid1.AppendRows()
        if not self.checkBox6.GetValue():
            self.muestraSucursalUnica(datos)
        else:
            self.muestraTodasSucursales(datos)

    def muestraSucursalUnica(self,datos):
        for fil,item in enumerate(datos):
            ptc = item["ptc"]
            codsussan = item["codsussan"]
            descripcion = item["descri"][:15]
            proveedor = item["nombre"][:20]+" / "+item["proveedor"]
            anio = str(item["anio"])
            talle = str(item["talle"])
            color = str(item["color"])
            try:
                nombrecolor = self.obtenerColor(color)
                color = nombrecolor+" / "+color
            except:
                color = str(item["color"])
            grupo = item["nombregrupo"]+" / "+item["grupo"]
            estacion = item["estacion"]
            stock = str(item["stock"])
            #ptc,codsussan,descripcion,proveedor,talle,color,grupo,estacion,anio,stock
            #0   1         2           3         4     5     6     7        8    9
            self.grid1.SetCellValue(fil,0,ptc)
            self.grid1.SetCellValue(fil,1,codsussan)
            self.grid1.SetCellValue(fil,2,descripcion)
            self.grid1.SetCellValue(fil,3,proveedor)
            self.grid1.SetCellValue(fil,4,talle)
            self.grid1.SetCellValue(fil,5,color)
            self.grid1.SetCellValue(fil,6,grupo)
            self.grid1.SetCellValue(fil,7,estacion)
            self.grid1.SetCellValue(fil,8,anio)
            self.grid1.SetCellValue(fil,9,stock)
            self.grid1.SetCellAlignment(fil, 9, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.AppendRows()

        self.ajustarAnchoColumnas()
        self.textCtrl3.SetLabel(str(self.grid1.GetNumberRows()-1))

    def buscarPTCenGrilla(self,ptc):
        for x in xrange(self.grid1.GetNumberRows()):
            if self.grid1.GetCellValue(x,0)==ptc:return x
        return -1
    
    def muestraTodasSucursales(self,datos):
        print "Muestra todas las sucursales",len(datos)
        fil = 0
        for item in datos:
            fila = fil
            ptc = item["ptc"]
            repetido = self.buscarPTCenGrilla(ptc)
            if repetido!=-1:
                fila = repetido
            codsussan = item["codsussan"]
            descripcion = item["descri"]
            proveedor = item["nombre"]+" / "+item["proveedor"]
            anio = str(item["anio"])
            talle = str(item["talle"])
            color = str(item["color"])
            try:
                nombrecolor = self.obtenerColor(color)
                color = nombrecolor+" / "+color
            except:
                color = str(item["color"])
            grupo = item["nombregrupo"]+" / "+item["grupo"]
            estacion = item["estacion"]
            sucursal = str(item["sucursal"])
            miCol = 8+int(sucursal)
            stock = str(item["stock"])

            #ptc,codsussan,descripcion,proveedor,talle,color,grupo,estacion,anio,Central,Parana,Saska,Peatonal
            #0   1         2           3         4     5     6     7        8    9       10     11    12
            self.grid1.SetCellValue(fila,0,ptc)
            self.grid1.SetCellValue(fila,1,codsussan)
            self.grid1.SetCellValue(fila,2,descripcion)
            self.grid1.SetCellValue(fila,3,proveedor)
            self.grid1.SetCellValue(fila,4,talle)
            self.grid1.SetCellValue(fila,5,color)
            self.grid1.SetCellValue(fila,6,grupo)
            self.grid1.SetCellValue(fila,7,estacion)
            self.grid1.SetCellValue(fila,8,anio)

            self.grid1.SetCellValue(fila,miCol,stock)
            self.grid1.SetCellAlignment(fila, miCol, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            if repetido==-1:
                self.grid1.AppendRows()
                fil = fil + 1

        self.ajustarAnchoColumnas()
        self.textCtrl3.SetLabel(str(self.grid1.GetNumberRows()-1))

    def OnImprimir(self, event):
        if self.checkBox6.GetValue():
            self.ImprimirVersion2()
            return
        print "Imprimir"
        f=open("c:\\erpsussan.doc\\reporte-BuscarArticuloPorProveedor.html","w")
        numeroPagina = 1
        nrosuc,nombresuc = utiles.datosSucursal()
        
        totalItemPorPagina = 38
        totalPaginas = int(self.grid1.GetNumberRows()-1) / totalItemPorPagina 
        totalPaginas+= 1

        def encabezadoPagina(texto):
            fecha = utiles.getfechaTime()
            estacion = self.comboBox1.GetLabel()
            anio = self.comboBox2.GetLabel()
            grupo = self.comboBox3.GetLabel()
            proveedor = self.textCtrl2.GetLabel()[:20]

            if estacion == "": estacion = "TODAS"
            if anio == "": anio = "TODOS"
            if grupo == "": grupo == "TODOS"
            
            a = '<table width="100%" cellspacing="0" border="0">\n'
            a+= '<tr>\n'
            a+= '<td valign="top" align="left" width="33%"><font size="0.1">'
            a+= 'SUSSAN BOUTIQUE Inventario<br>'+nombresuc+'</font></td>\n'
            a+= '<td valign="top" align="left" width="34%"><font size="0.1">'
            a+= 'Proveedor: '+proveedor+' Estaci&oacute;n: '+estacion+'<br>'
            a+= 'A&ntilde;o:'+anio+' Grupo: '+grupo+'</font></td>\n'
            a+= '<td valign="top" align="right" width="33%"><font size="0.1">'+fecha
            a+= '<br>P&aacute;gina '+str(numeroPagina)+' / '+str(totalPaginas)+'</font></td>\n'
            a+= '</tr>\n'
            a+= '</table></font>\n'
            a+= '<hr>\n'
            texto+= a
            return texto
        
        def encabezadoTabla(texto):
            a = '<table width="100%" cellspacing="1" border="0"> \n'
            a+= '<tr>\n'
            a+= '<td valign="top" align="left"><font size="0.1">orden</font></td>\n'
            a+= '<td valign="top" align="center"><font size="0.1">P.T.C.</font></td>\n'
            a+= '<td valign="top" align="center"><font size="0.1">Cod.<br>Sussan</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">DESCRIPCION</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">Proveedor</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">Talle</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">Color</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">Grupo</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">Estacion</font></td>\n'
            a+= '<td valign="top" align="center"><font size="0.1">A&ntilde;o</font></td>\n'
            a+= '<td valign="top" align="right"><font size="0.1">STOCK</font></td> \n'
            a+= '</tr>\n'
            a+= '<tr>\n'
            a+= '<td colspan="11"><hr></td>\n'
            a+= '</tr>\n'
            texto+= a
            return texto
        
        cadena = '<?xml version="1.0" encoding="utf-8" ?> \n'
        cadena+= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> \n'
        cadena+= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> \n'
        cadena+= '<head> \n'
        cadena+= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> \n'
        cadena+= '<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" /> \n'
        cadena+= '<title>Sussan Boutique</title> \n'
        cadena+= '</head> \n'
        cadena+= '<body> \n'

        cadena = encabezadoPagina(cadena)
        cadena = encabezadoTabla(cadena)
        f.write(cadena)
        
        renglon = 0
        for i in xrange(self.grid1.GetNumberRows()-1):
        #PTC,CodSussan,Descripcion,Talle,Color,Stock\nCentral,Stock\nParana,Stock\nSaska,Stock\nPeatonal
            ptc = self.grid1.GetCellValue(i,0)
            codsussan = self.grid1.GetCellValue(i,1)
            descripcion = (self.grid1.GetCellValue(i,2))[:40]
            proveedor = (self.grid1.GetCellValue(i,3))[:12]
            talle = self.grid1.GetCellValue(i,4)
            color = self.grid1.GetCellValue(i,5)
            grupo = (self.grid1.GetCellValue(i,6))[:20]
            estacion = self.grid1.GetCellValue(i,7)
            anio = self.grid1.GetCellValue(i,8)
            stock = self.grid1.GetCellValue(i,9)
            alineacion = '"center"'
            if self.textCtrl1.GetLabel()=="*":
                alineacion = '"left"'
            
            orden = str(i+1)

            cadena = '<tr>\n'
            cadena+= '<td valign="center" align="center"><font size="0.1">'+orden+'</font></td> \n'
            cadena+= '<td valign="center" align="center">'+ptc+'</td> \n'
            cadena+= '<td valign="center" align="center">'+codsussan+'</td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+descripcion+'</font></td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+proveedor+'</font></td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+talle+'</font></td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+color+'</font></td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+grupo+'</font></td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+estacion+'</font></td> \n'
            cadena+= '<td valign="center" align="center"><font size="0.1">'+anio+'</font></td> \n'
            cadena+= '<td valign="center" align="right">'+stock+'</td> \n'
            cadena+= '</tr>\n'
            try:
                f.write(cadena)
            except:
                print cadena
            
            renglon+= 1
            
            if renglon >= totalItemPorPagina :
                f.write("</table><!-- salto de pagina -->\n")
                f.write("<p STYLE='page-break-after: always;'></p>\n")
                renglon = 0
##                for i in xrange(numeroPagina):
##                    f.write("<br>\n")
                numeroPagina+= 1
                cadena = encabezadoPagina("")
                cadena = encabezadoTabla(cadena)
                f.write(cadena)
            
        cadena = '</table>\n'
        cadena+= '<br>Total &iacute;tems: '+str(self.grid1.GetNumberRows()-1)+'\n'
        cadena+= '<br>Total p&aacute;ginas: '+str(numeroPagina)+'\n'
        cadena+= '</body>\n</html>\n'
        f.write(cadena)
        f.close()

        self.button2.SetFocus()

        import os
        os.system("taskkill /IM firefox.exe /F")
        os.system("c:\\explorer.lnk c:\\erpsussan.doc\\reporte-BuscarArticuloPorProveedor.html")

    def OnCheck6(self, event):
        if self.checkBox6.GetValue():
            self.grid1.AppendCols()
            self.grid1.AppendCols()
            self.grid1.AppendCols()
            columnas = ['P.T.C','Codigo\nSussan','Descripcion','Proveedor',\
                        'Talle','Color','Grupo','Estacion','Anio','Cent',\
                        'Pna','Saska','Peat']
            for i, col in enumerate(columnas): 
                self.grid1.SetColLabelValue(i, col)
            self.ajustarAnchoColumnas()
            self.grid1.ClearGrid()
            for fil in xrange(self.grid1.GetNumberRows()):
                self.grid1.DeleteRows()
            self.grid1.AppendRows()
            self.checkBox1.Enable(False)
            self.checkBox2.Enable(False)
            self.checkBox3.Enable(False)
            self.checkBox1.SetValue(False)
            self.checkBox2.SetValue(True)
            self.checkBox3.SetValue(False)
        else:
            self.grid1.DeleteCols()
            self.grid1.DeleteCols()
            self.grid1.DeleteCols()
            columnas = ['P.T.C','Codigo\nSussan','Descripcion','Proveedor',\
                        'Talle','Color','Grupo','Estacion','Anio','Stock']
            for i, col in enumerate(columnas): 
                self.grid1.SetColLabelValue(i, col)
            self.ajustarAnchoColumnas()
            self.grid1.ClearGrid()
            for fil in xrange(self.grid1.GetNumberRows()):
                self.grid1.DeleteRows()
            self.grid1.AppendRows()
            self.checkBox1.Enable(True)
            self.checkBox2.Enable(True)
            self.checkBox3.Enable(True)
            self.checkBox1.SetValue(False)
            self.checkBox2.SetValue(True)
            self.checkBox3.SetValue(False)

    def ImprimirVersion2(self):
        print "Imprimir todas las sucursales"
        f=open("c:\\erpsussan.doc\\reporte-BuscarArticuloPorProveedor.html","w")
        numeroPagina = 1
        nrosuc,nombresuc = utiles.datosSucursal()
        
        totalItemPorPagina = 38
        totalPaginas = int(self.grid1.GetNumberRows()-1) / totalItemPorPagina 
        totalPaginas+= 1

        def encabezadoPagina(texto):
            fecha = utiles.getfechaTime()
            estacion = self.comboBox1.GetLabel()
            anio = self.comboBox2.GetLabel()
            grupo = self.comboBox3.GetLabel()
            proveedor = self.textCtrl2.GetLabel()[:20]

            if estacion == "": estacion = "TODAS"
            if anio == "": anio = "TODOS"
            if grupo == "": grupo == "TODOS"
            
            a = '<table width="100%" cellspacing="0" border="0">\n'
            a+= '<tr>\n'
            a+= '<td valign="top" align="left" width="33%"><font size="0.1">'
            a+= 'SUSSAN BOUTIQUE Inventario<br>'+nombresuc+'</font></td>\n'
            a+= '<td valign="top" align="left" width="34%"><font size="0.1">'
            a+= 'Proveedor: '+proveedor+' Estaci&oacute;n: '+estacion+'<br>'
            a+= 'A&ntilde;o:'+anio+' Grupo: '+grupo+'</font></td>\n'
            a+= '<td valign="top" align="right" width="33%"><font size="0.1">'+fecha
            a+= '<br>P&aacute;gina '+str(numeroPagina)+' / '+str(totalPaginas)+'</font></td>\n'
            a+= '</tr>\n'
            a+= '</table></font>\n'
            a+= '<hr>\n'
            texto+= a
            return texto
        
        def encabezadoTabla(texto):
            a = '<table width="100%" cellspacing="1" border="0"> \n'
            a+= '<tr>\n'
            a+= '<td valign="top" align="left"><font size="0.1">orden</font></td>\n'
            a+= '<td valign="top" align="center"><font size="0.1">P.T.C.</font></td>\n'
            a+= '<td valign="top" align="center"><font size="0.1">Cod.<br>Sussan</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">DESCRIPCION</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">Proveedor</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">Talle</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">Color</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">Grupo</font></td>\n'
            a+= '<td valign="top" align="left"><font size="0.1">Estacion</font></td>\n'
            a+= '<td valign="top" align="center"><font size="0.1">A&ntilde;o</font></td>\n'
            a+= '<td valign="top" align="right"><font size="0.1">Cent</font></td> \n'
            a+= '<td valign="top" align="right"><font size="0.1">Pna</font></td> \n'
            a+= '<td valign="top" align="right"><font size="0.1">Sask</font></td> \n'
            a+= '<td valign="top" align="right"><font size="0.1">Peat</font></td> \n'
            a+= '</tr>\n'
            a+= '<tr>\n'
            a+= '<td colspan="14"><hr></td>\n'
            a+= '</tr>\n'
            texto+= a
            return texto
        
        cadena = '<?xml version="1.0" encoding="utf-8" ?> \n'
        cadena+= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> \n'
        cadena+= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> \n'
        cadena+= '<head> \n'
        cadena+= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> \n'
        cadena+= '<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" /> \n'
        cadena+= '<title>Sussan Boutique</title> \n'
        cadena+= '</head> \n'
        cadena+= '<body> \n'

        cadena = encabezadoPagina(cadena)
        cadena = encabezadoTabla(cadena)
        f.write(cadena)
        
        renglon = 0
        for i in xrange(self.grid1.GetNumberRows()-1):
        #PTC,CodSussan,Descripcion,Talle,Color,Stock\nCentral,Stock\nParana,Stock\nSaska,Stock\nPeatonal
            ptc = self.grid1.GetCellValue(i,0)
            codsussan = self.grid1.GetCellValue(i,1)
            descripcion = (self.grid1.GetCellValue(i,2))[:35]
            proveedor = (self.grid1.GetCellValue(i,3))[:10]
            talle = self.grid1.GetCellValue(i,4)
            color = self.grid1.GetCellValue(i,5)
            grupo = (self.grid1.GetCellValue(i,6))[:20]
            estacion = self.grid1.GetCellValue(i,7)
            anio = self.grid1.GetCellValue(i,8)
            cent = self.grid1.GetCellValue(i,9)
            pna  = self.grid1.GetCellValue(i,10)
            sask = self.grid1.GetCellValue(i,11)
            peat = self.grid1.GetCellValue(i,12)
            if cent == "":cent = "0"
            if pna  == "":pna  = "0"
            if sask == "":sask = "0"
            if peat == "":peat = "0"

            alineacion = '"center"'
            if self.textCtrl1.GetLabel()=="*":
                alineacion = '"left"'
            
            orden = str(i+1)

            cadena = '<tr>\n'
            cadena+= '<td valign="center" align="center"><font size="0.1">'+orden+'</font></td> \n'
            cadena+= '<td valign="center" align="center">'+ptc+'</td> \n'
            cadena+= '<td valign="center" align="center">'+codsussan+'</td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+descripcion+'</font></td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+proveedor+'</font></td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+talle+'</font></td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+color+'</font></td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+grupo+'</font></td> \n'
            cadena+= '<td valign="center" align="left"><font size="0.1">'+estacion+'</font></td> \n'
            cadena+= '<td valign="center" align="center"><font size="0.1">'+anio+'</font></td> \n'
            cadena+= '<td valign="center" align="right">'+cent+'</td> \n'
            cadena+= '<td valign="center" align="right">'+pna +'</td> \n'
            cadena+= '<td valign="center" align="right">'+sask+'</td> \n'
            cadena+= '<td valign="center" align="right">'+peat+'</td> \n'
            cadena+= '</tr>\n'
            try:
                f.write(cadena)
            except:
                print cadena
            
            renglon+= 1
            
            if renglon >= totalItemPorPagina :
                f.write("</table><!-- salto de pagina -->\n")
                f.write("<p STYLE='page-break-after: always;'></p>\n")
                renglon = 0
##                for i in xrange(numeroPagina):
##                    f.write("<br>\n")
                numeroPagina+= 1
                cadena = encabezadoPagina("")
                cadena = encabezadoTabla(cadena)
                f.write(cadena)
            
        cadena = '</table>\n'
        cadena+= '<br>Total &iacute;tems: '+str(self.grid1.GetNumberRows()-1)+'\n'
        cadena+= '<br>Total p&aacute;ginas: '+str(numeroPagina)+'\n'
        cadena+= '</body>\n</html>\n'
        f.write(cadena)
        f.close()

        self.button2.SetFocus()

        import os
        os.system("taskkill /IM firefox.exe /F")
        os.system("c:\\explorer.lnk c:\\erpsussan.doc\\reporte-BuscarArticuloPorProveedor.html")

    def OnCambiaRubro(self, event):
        if self.comboBox4.GetSelection()<=0:
            self.comboBox3.Enable(True)
        else:
            self.comboBox3.Enable(False)
            self.comboBox3.SetSelection(-1)
        
        
